<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-08-17
 * Time: 18:14
 */
class b2c_ctl_site_orderaddtimer extends b2c_frontpage{
    function __construct($app){
        parent::__construct($app);
        $this->secret = '64f420a7-432b-4d17-824b-ceb3a686a3ec';
        $this->appkey = '249d3566-f51f-43c4-aa0f-6ddf32e8fb4e';
        $this->format = 'json';
        $this->v = '1.0';
        $this->token = 'c4cad18f-2e8f-467d-b4ec-da511b6949e9';
        $this->url = "http://120.26.115.70:6060/wtdex-service/ws/openapi/rest/route";
    }

    function ordersadd (){

        $sql = "select o.*,g.goods_id,g.tip_id,oi.order_id,oi.bn,oi.name,oi.nums,oi.price,oi.amount from sdb_b2c_orders as o
left join sdb_b2c_order_items as oi on o.order_id = oi.order_id
left join sdb_b2c_goods as g on oi.goods_id = g.goods_id
where o.ship_status = '0' and o.pay_status= '1' and o.status='active' and o.is_send_customs = '0' and (g.tip_id = '3' or g.tip_id = '4') and (o.cardnum is NOT NULL or o.cardnum != '') group by o.order_id";
        $arr1 = kernel::database()->select($sql);

//        查询订单商品表，每个订单号内的商品信息
        $arr2 = $arr1;
//        $sql = "select i.order_id,i.product_id,i.name,i.nums,i.price,i.amount from ".kernel::database()->prefix."b2c_order_items as i
//                left join ".kernel::database()->prefix."b2c_orders as o on i.order_id = o.order_id";
//        $arr2 = kernel::database()->select($sql);

//        遍历订单商品数组，返回以订单号为下标的二维数组
        $num = count($arr2);
        foreach ($arr2 as $k => $value) {
//            先判断该下标的元素是否存在，存在则以该元素的订单号为下标组成一个新的数组，否则跳过该次循环
            if(!empty($arr2[$k])){
                $data[$value['order_id']][] = $value;
//                再遍历订单商品表
                for($i = $k+1;$i < count($arr2);$i++){
//                    先判断外循环的元素是否存在
                    if(!empty($arr2[$i])){
//                        接着判断外循环元素的订单号与内循环元素的订单号是否一致
                        if($value['order_id']==$arr2[$i]['order_id']){
//                            一致则添加进新的数组，组合成接口参数
                            $data[$value['order_id']][] = $arr2[$i];
//                            删除比较过的订单商品数组的元素
                            unset($arr2[$k],$arr2[$i]);
                        }
                    }
                }
            }else{
                continue;
            }
        }
        $param =array();
//        嵌套循环订单数组和订单商品数组
        $j = 0;
        foreach ($arr1 as $k => $value) {
            foreach ($data as $oid => $goods) {
                if($value['order_id'] == $oid){
                    //          将订单表的ship_area字段值拆分成省，市，区
                    $ship_area = explode(':',str_replace('mainland:','',$arr1[$k]['ship_area']));
                    $ship_area = explode('/',$ship_area[0]);


                    $goods_total_price = 0;
                    $orderItemList = array();
                    //   组合orderItemList参数
                    foreach ($goods as $key => $val) {
                        $orderItemList['orderItems'][$key]['productId'] = $val['bn'];//商品编码
                        $orderItemList['orderItems'][$key]['productName'] = $val['name'];//商品名称
                        $orderItemList['orderItems'][$key]['qty'] = $val['nums'];//商品数量
                        $orderItemList['orderItems'][$key]['price'] = $val['price'];//商品单价
                        $orderItemList['orderItems'][$key]['total'] = $val['amount'];//付款金额

                        $goods_total_price += $val['amount'];
                    }

                    $param['orders'][$j] = array(
                        'orderId' => $value['order_id'],//订单号
                        'orderDate' => date("Y-m-d H:i:s",$value['createtime']),//订单日期
                        'name' => $value['ship_name'],//顾客姓名
                        'province' => $ship_area[0],//送货省
                        'city' => $ship_area[1],//送货市
                        'area' => $ship_area[2],//送货区/县
                        'addr' => $value['ship_addr'],//送货地址
                        'cardType' => '0',//证件类型
                        'cardNo' => $value['cardnum'],//顾客身份证
                        'phone' => $value['ship_mobile'],//联系电话1
                        'total' => $goods_total_price,//订单总金额(待确定)
                        'freight' => $value['cost_freight'],//运费
                        'insuredFee' => $value['cost_protect'],//保价费用
                        'portCode' => '5141',//口岸编码
                        'busiMode' => 'BC',//所属业务模式
                        'whCode' => 'HKFL',//发货仓库代号
                        'pickMode' => 0,
                        'expressCode' => 'YT',//物流公司编码
                        'orderItemList' => $orderItemList,
                    );

                    $j = $j+1;
                }
            }
        }


        $method = 'wtdex.trade.order.batch';
        $secret = $this->secret;
        $appkey = $this->appkey;
        $format = $this->format;
        $parm = json_encode($param);
        $time = date("Y-m-d H:i:s",time());
        $v = $this->v;
        $token = $this->token;

        $sign = "{$secret}{$appkey}{$format}{$method}{$parm}{$time}{$token}{$v}{$secret}";
        $sign = base64_encode(strtolower(md5($sign)));
//        生成url，post参数
        $url = $this->url;
        $post_arr = array(
            'appkey' => $appkey,
            'sign' => $sign,
            'token' => $token,
            'v' => $v,
            'format' => $format,
            'method' => $method,
            'timestamp' => $time,
            'params' => $parm,
        );
//        用curl函数模拟post请求，最后关闭curl对象
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_arr);
        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res);
    }

    //    查询订单物流信息，若信息码显示为50，则以发货，将本地的未发货订单的状态改为已发货
    public function checkorder(){
        //        查询所有订单表的新数据
        $filter = array(
            'ship_status'=>'0',
            'pay_status'=>'1',
            'status'=>'active'
        );
        $res = app::get('b2c')->model('orders')->getlist('*',$filter);
        foreach($res as $value){
            $arr = $this->order_exp($value['order_id']);
            $state = $arr->response->expressRoute->expressRouteItemList->expressRouteItems['state'];
            if(!empty($state) && $state == '50'){
                $filter = array(
                    'order_id'=>$value['order_id'],
                );
                $data = array(
                    'ship_status'=> '1',
                );
                app::get('b2c')->model('orders')->update($data,$filter);
            }
        }

    }

    //    返回用户对应订单的物流信息
    function order_exp($orderid)
    {
        //生成时间戳，传递参数，组合sign签名,再加密
        $time = date("Y-m-d H:i:s", time());
        $param = array(
            'orderId' => $orderid,
        );
        $parm = json_encode($param);
        $method = 'wtdex.trade.express.get';
        $secret = $this->secret;
        $appkey = $this->appkey;
        $format = $this->format;
        $v = $this->v;
        $token = $this->token;
        $sign = "{$secret}{$appkey}{$format}{$method}{$parm}{$time}{$token}{$v}{$secret}";
        $sign = base64_encode(strtolower(md5($sign)));
//        生成url，post参数
        $url = $this->url;
        $post_arr = array(
            'appkey' => $appkey,
            'sign' => $sign,
            'token' => $token,
            'v' => $v,
            'format' => $format,
            'method' => $method,
            'timestamp' => $time,
            'params' => $parm,
        );
//        用curl函数模拟post请求，最后关闭curl对象
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_arr);
        $data = curl_exec($curl);
        curl_close($curl);
//        对接口返回的$data进行json解码
        $data = json_decode($data);
        return $data;
    }
}